import axios from "axios";
import qs from "qs";
import DES from "@/utils/des";
import { message } from "antd";
// import { useUserStore } from "@/store/user";
import { getUser, getToken, clearToken, clearUserInfo } from "@/utils/local";
import store, { storeSetToken, storeSetUserInfo } from "@/store";
import router from "@/router";
const VITE_NO_ACCESS_TOKEN = import.meta.env.VITE_NO_ACCESS_TOKEN;

const service = axios.create({
  timeout: 20000,
  baseURL: import.meta.env.VITE_APP_BASE_API,
  headers: {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "*",
    "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
    "Access-Control-Allow-Credentials": true,
  },
});

const reqLoad = (function () {
  let loginmsging = false;
  const loginErr = function () {
    if (!loginmsging) {
      loginmsging = true;
      message.error("登录失效,需重新登录后使用", 1, () => {
        loginmsging = false;
      });
      if (VITE_NO_ACCESS_TOKEN === "true") {
        return;
      }
      store.dispatch(storeSetToken(null));
      store.dispatch(storeSetUserInfo(null));
      clearToken();
      clearUserInfo();
      router.navigate("/login", { replace: true });
    }
  };
  return {
    loginErr,
  };
})();

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    const method = config.method || "get";
    const userStore = {
      accessToken: getToken(),
    };
    if (method.toLowerCase() == "get") {
      config.params = config.params || {};
    } else {
      config.data = qs.parse(config.data);
    }
    if (userStore.accessToken) {
      config.headers.token = userStore.accessToken;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    if (Number(response.data.code) === 401) {
      reqLoad.loginErr();
      return response;
    }
    if (response.config.needDecrypt === 'true') {
      const userStore = {
        userInfo: getUser(),
      };
      response.data.data = JSON.parse(
        DES.decryptECB(response.data.data, userStore.userInfo.des_uuid)
      );
    }
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const request = async (config) => {
  try {
    const res = await service.request(config);
    return res.data;
  } catch (err) {
    const message = err.message || "请求失败";
    return {
      code: -1,
      message,
      data: null,
    };
  }
};

export default request;
